package com.yang.qgg_demo.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.yang.qgg_demo.controller.dto.UserDTO;
import com.yang.qgg_demo.entity.User;
import com.yang.qgg_demo.mapper.UserMapper;
import com.yang.qgg_demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * 生成token
 */
@Component
public class TokenUtils {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private static IUserService staticUserMapper;

//    @PostConstruct
//    public void init() {
//        staticUserMapper = userMapper;
//    }


    public static String genToken1(Integer userId, String sign) throws UnsupportedEncodingException {
        return JWT.create().withAudience(String.valueOf(userId))//将 user id保存到Token里面，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))//2小时后token过期
                .sign(Algorithm.HMAC256(sign));//以password作为token的密钥
    }

    public static String genToken2(UserDTO userId, String sign) throws UnsupportedEncodingException {
        return JWT.create().withAudience(String.valueOf(userId))//将 user id保存到Token里面，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))//2小时后token过期
                .sign(Algorithm.HMAC256(sign));//以password作为token的密钥
    }

    /**
     * 获取当前登录的用户信息
     */
    public static String getUser() {
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if(StrUtil.isNotBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                return userId;
            }
        }catch (Exception e){
            return null;
        }

        return null;
    }

}
